package com.situ.mall.config;

import com.situ.mall.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    //拦截所有请求
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/page/login", "/admin/login", "/admin/logout", "/auth/code", "/static/**");
    }

    //配置虚拟路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pic/**")
                .addResourceLocations("file:/D:/mypic/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }


    @Override
    public void addFormatters(FormatterRegistry registry) {
        String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

        //Alt+Enter
        registry.addConverter(new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                try {
                    return new SimpleDateFormat(DATETIME_FORMAT).parse(source);
                } catch (ParseException e) {
                    //throw new RuntimeException("时间转换失败：" + source, e);
                    e.printStackTrace();
                }
                return null;
            }
        });
    }
}

